package com.tau.egonetwork.gui.linkedin;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Shell;

import com.tau.egonetwork.common.Log;
import com.tau.egonetwork.gui.core.EgoNetworkMessageBox;
import com.tau.egonetwork.gui.interfaces.IPopupAnswerToTab;
import com.tau.egonetwork.gui.interfaces.IPopupResponse;
import com.tau.egonetwork.gui.interfaces.IRequestGUI;
import com.tau.egonetwork.linkedin.LinkedinAuthRequest;
import com.tau.egonetwork.threads.LinkedinThread;

public class LinkedinPopupResponse implements IPopupResponse {

	private final static String FAILURE_URL = "about:blank";
	private final static String DENIED_URL = LinkedinAuthRequest.REDIRECT + "?error=access_denied";
	private final static String SUCCESS_URL = LinkedinAuthRequest.REDIRECT;

	private Shell _parent;
	private Shell _popupShell;
	private IPopupAnswerToTab _popupAnswerToTab;
	private IRequestGUI _linkedinRequestGUI;
		
	public LinkedinPopupResponse(Shell parent, IPopupAnswerToTab answer, IRequestGUI linkedinGUIRequest) {
		_parent = parent;
		_popupAnswerToTab = answer;
		_linkedinRequestGUI = linkedinGUIRequest;
	}

	@Override
	public boolean onPopupResponse(String response) {
		Log.writeLineToLog("LinkedinPopupResponse: " + response);

		if (response.equals(FAILURE_URL)) {
			
			//user failed to enter correct login data several times:
			
			//first hide the popup:
			_popupShell.setVisible(false);
			
			//tell the user and ask him what to do:
			EgoNetworkMessageBox dialog = new EgoNetworkMessageBox(_parent, SWT.ICON_QUESTION, SWT.RETRY | SWT.CANCEL);
        	dialog.setText("Linkedin Access");
        	dialog.setMessage("You have made several repeated failed attempts to access Linkedin. Would you like to try again?");
        	int code = dialog.open();
        	
        	if (code == SWT.RETRY) {
        		if (_popupAnswerToTab != null)
            		_popupAnswerToTab.popupClosedWithCode(SWT.RETRY);
        	}
        	//else: user selected cancel (or exited using "X") --> close popup, do nothing        	
        	
        	//close popup no matter what (new one might be issued if Retry):
    		return true;
        	
		} else if (response.startsWith(DENIED_URL, 0)) {
			//user denied to give us access - close the popup
			return true;
		} else if (response.startsWith(SUCCESS_URL, 0)) {
			
			//success! -> user entered correct data and has approved us :)
			
			//first of all hide pop-up:
			_popupShell.setVisible(false);
			
			{
				//check that state matches (no CSRF):
				int pattern = response.indexOf("state=") + "state=".length();
				int atEnd = response.lastIndexOf("&");
				String state = "";
				if (atEnd > pattern) {
					state = response.substring(pattern, atEnd);
				} else {
					state = response.substring(pattern);
				}
				if (!state.equals(LinkedinAuthRequest.STATE)) {
					//CSRF error occurred.. FRAK! notify user he must try again through no fault of his own:
					EgoNetworkMessageBox dialog = new EgoNetworkMessageBox(_parent, SWT.ICON_ERROR, SWT.OK);
		        	dialog.setText("Linkedin Access");
		        	dialog.setMessage("A rare collision has occurred on Linkedin Server :( Please try again, the error should not re-emerge. Sorry for the inconvience.");
		        	dialog.open();
		        	//close popup!:
					return true;
				}
			}
			
			//no CRSF error, extract code and invoke thread:
			String pattern = "?code=";
			String code = response.substring(response.indexOf(pattern) + pattern.length());
			//could be that the return pattern was ?code=****&state=****, remove state attribute:
			if (code.contains("&state="))
				code = code.substring(0, code.indexOf("&state="));
			
			LinkedinThread.invoke(_parent, code, _linkedinRequestGUI);
			
			//close popup:
			return true;
		}
		
		//for any other case, we might be facing a redirection, or
		//a failed attempt with another shot or anything else
		//-- do not close the popup!:
		return false;
	}

	@Override
	public void registerPopup(Shell popupShell) {
		_popupShell = popupShell;
	}
	
}
